package cn.cdeden.resource.dubbo;

import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.oss.core.OssClientBucket;
import cn.cdeden.common.oss.factory.OssFactory;
import cn.cdeden.resource.api.RemoteOssEsService;
import cn.cdeden.resource.api.domain.RemoteEsFilesTree;
import cn.cdeden.resource.domain.SysOssEs;
import cn.cdeden.resource.domain.vo.SysOssVo;
import cn.cdeden.resource.service.ISysOssService;
import cn.cdeden.resource.service.OssFileEsService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.Base64;

/**
 * @ProjectName : KnowCore
 * @Package : cn.cdeden.resource.dubbo
 * @ClassName : RemoteOssEsServiceImpl
 * @Author : Yu.
 * @Description : // TODO
 * @Date : 2024/12/12 10:49
 * @Version : 1.0
 */
@Slf4j
@RequiredArgsConstructor
@Service
@DubboService
//@ConditionalOnProperty(value = "easy-es.enable", havingValue = "true")
public class RemoteOssEsServiceImpl implements RemoteOssEsService {


//    private final SysOssEsMapper ossEsMapper;  //我没有找到添加数据满足 es 索引的场景，所以没有使用

    /**
     * 自定义 使用es方法
     */
//    private final EsDataOperation operation;
    @Autowired(required = false)
    private OssFileEsService ossEsService;

    private final ISysOssService ossService;

    @Value("${easy-es.enable:false}")
    private Boolean enable; //畅写地址
    @Override
    public boolean esEnabled() {
        if (ossEsService != null){
            return enable;
        }
        return false;
    }

    @Override
    public boolean deleteById(String id) {
        try {
            return ossEsService.deleteById(id);
        }catch (Exception e){
            log.error("删除es文件树数据失败",e);
        }
        return Boolean.FALSE;
    }

    /**
     * 更新es中文件树的数据
     *
     * @param filesTree
     * @return cn.cdeden.resource.api.domain.RemoteEsFilesTree
     * @author Yu.
     * @Date 2024/12/12 10:40
     **/
    @Override
    public String update(RemoteEsFilesTree filesTree) {
        String esId = filesTree.getEsId();
        if (esId == null){
            throw new RuntimeException("esId为空");
        }
        String storageId = filesTree.getStorageId();
        String content = "";
        if (storageId != null){
            SysOssVo ossVo = ossService.getById(Long.valueOf(storageId));
            if (ObjectUtil.isNull(ossVo)){
                throw new ServiceException("oss文件不存在");
            }else if(ossVo.getModuleType().equals(filesTree.getLibraryType())){

            }
                Long fileSize = ossVo.getFileSize();
            if (fileSize < 1024 * 1024 * 70  ){ //大于80M的文件不加入es查询
                OssClientBucket storage = OssFactory.instanceBucket(ossVo.getService());
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                long download = storage.downloadAsynchronous(ossVo.getBucketName(), ossVo.getFileName(), ossVo.getVersionId(), outputStream);
                content = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            }
        }

        SysOssEs build = SysOssEs.builder()
            .id(esId)
            .content("") //文档内容
            .moduleId(String.valueOf(filesTree.getId())) //文件id
            .type(filesTree.getType()) //文件类型
            .moduleType(filesTree.getLibraryType()) //文件模块类型
            .title(filesTree.getRealName())
            .fileSuffix(filesTree.getSuffix())
            .teamId(filesTree.getTeamId())
            .content(content)
            .userIdList(filesTree.getUserIdList())
            .deptIdList(filesTree.getDeptIdList())
            .roleIdList(filesTree.getRoleIdList())
            .postIdList(filesTree.getPostIdList())
            .versionId(filesTree.getVersionId() != null ? filesTree.getVersionId() : "")
            .versionName(filesTree.getVersionName() != null ? filesTree.getVersionName() : "")
            .createBy(filesTree.getCreateBy()) //创建人
            .createTime(filesTree.getCreateTime()) //创建时间
            .updateBy(filesTree.getUpdateBy()) //更新人
            .updateTime(filesTree.getUpdateTime()) //更新时间
            .build();
        if (ossEsService!= null){
            boolean b = ossEsService.updateById(build);
            return esId;
        }else {
            return null;
        }

    }




    /**
     * 新增 es中文件树的数据
     *
     * @param filesTree
     * @return boolean
     * @author Yu.
     * @Date 2024/12/12 10:42
     **/
    @Override
    public String insert(RemoteEsFilesTree filesTree) {
        String storageId = filesTree.getStorageId();
        String content = "";
        if (storageId != null){
            SysOssVo ossVo = ossService.getById(Long.valueOf(storageId));
            if (ObjectUtil.isNull(ossVo)){
                throw new ServiceException("oss文件不存在");
            }
            Long fileSize = ossVo.getFileSize();
            if (fileSize < 1024 * 1024 * 70  ){ //大于80M的文件不加入es查询
                OssClientBucket storage = OssFactory.instanceBucket(ossVo.getService());
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                long download = storage.downloadAsynchronous(ossVo.getBucketName(), ossVo.getFileName(), ossVo.getVersionId(), outputStream);
                content = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            }
        }

        String uuid = filesTree.getEsId();
        if (uuid == null){
            uuid = IdUtil.simpleUUID();
        }

        SysOssEs build = SysOssEs.builder()
            .id(uuid)
            .moduleId(String.valueOf(filesTree.getId())) //文件id
            .type(filesTree.getType()) //文件类型
            .moduleType(filesTree.getLibraryType()) //文件模块类型
            .title(filesTree.getRealName())
            .fileSuffix(filesTree.getSuffix())
            .versionId(filesTree.getVersionId() != null ? filesTree.getVersionId() : "")
            .versionName(filesTree.getVersionName() != null ? filesTree.getVersionName() : "")
            .userIdList(filesTree.getUserIdList())
            .deptIdList(filesTree.getDeptIdList())
            .roleIdList(filesTree.getRoleIdList())
            .postIdList(filesTree.getPostIdList())
            .teamId(filesTree.getTeamId())
//            .createDept(ossVo.getCreateDept())
            .content(content) //文档内容
            .createBy(filesTree.getCreateBy()) //创建人
            .createTime(filesTree.getCreateTime()) //创建时间
            .updateBy(filesTree.getUpdateBy()) //更新人
            .updateTime(filesTree.getUpdateTime()) //更新时间
            .build();

        if (ossEsService!= null){
            boolean b = ossEsService.insert(build);
            return  b ? uuid : null;
        }else {
            return null;
        }
    }
}
